package org.jugile.util;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ""
 * 
 * @author jukka.rahkonen@iki.fi
 */
public class Profiler {

	private static volatile ConcurrentHashMap<String,Entry> entries = new ConcurrentHashMap<String,Entry>();

	public static Timer start(Object cl, String methodname) {
		String name = "";
		if (cl instanceof String) {
			name = (String)cl;
		} else {
			name = cl.getClass().getName();
		}
		return new Timer(name, methodname);
	}

	public static void stop(Timer t) {
		Entry e = entries.get(t.getKey());
		if (e == null) {
			e = new Entry(t);
			entries.put(t.getKey(), e);
		}
		// update entry
		e.update(t);
	}
	
	public static void lap(Timer t) {
		stop(t); // same update than with stop
	}

	public static void reset() {
		entries = new ConcurrentHashMap<String,Entry>();
	}

	public static String dump() {
		StringBuffer buf = new StringBuffer();
		for (Entry e : entries.values()) {
			buf.append(e.toString() + "\n");
		}
		return buf.toString();
	}
	
	protected static class Entry {
		private String name;
		int callcount = 0;
		long sum = 0L;
		
		public Entry(Timer t) {
			name = t.getKey();
		}
		
		public void update(Timer t) {
			callcount++;
			sum += t.getDuration();
		}
		
		public long getAverage() {
			if (callcount == 0) return 0;
			return sum / callcount;
		}
		
		public String toString() {
			String res = name + "\t"
			+ "avg: " + getAverage() + "\t"
			+ "ccount: " + callcount + "\t"
			+ "sum: " + sum + "\t"
			;
			return res;
		}
	}
	
}
